<?php

namespace app\user\controller\device;

use app\BaseController;
use app\common\controller\Mqtt;
use app\user\model\Device;
use app\user\model\Devicetrends;
use app\user\model\Imei;
use app\user\model\User;
use think\Request;

class Index extends BaseController
{
    // 删除设备
    public function delDevice(Request $request)
    {
        $param = $request->param();
        $deviceId = $param['id'];
        $uid = $request->user_id;
        $deviceModel = new Device();
        $imeiModel = new Imei();
        $trendsModel = new Devicetrends();
        $userModel = new User();
        $up = $deviceModel->getUpdate(['id' => $deviceId], ['datastatus' => $deviceModel::DEL_DATASTATUS, 'dtime' => time()]);
        if ($up) {
            // 减少用户设备数量 
            $userModel->where(['id' => $uid])->setDec('device_num');
            // 释放imei
            upImei($deviceId, 'status', $imeiModel::DEVICE_BIND_STATUS_NO);
            // 清除所有动态
            $trendsModel->where(['device_id' => $deviceId])->update(['datastatus' => $trendsModel::DEL_DATASTATUS]);
            return success([]);
        }
        return fail([], '(UPDATE ERROR)更新错误');
    }

    // 修改设备名
    public function editDeviceName(Request $request)
    {
        $param = $request->param();
        $deviceId = $param['id'];
        $deviceName = $param['name'];
        $deviceModel = new Device();
        $edit = $deviceModel->getUpdate(['id' => $deviceId], ['device_name' => $deviceName]);
        if ($edit) {
            return success([]);
        } else {
            return fail([], '(UPDATE ERROR)更新错误');
        }
    }

    // 切换模式
    public function editDeviceModel(Request $request)
    {
        $param = $request->param();
        $deviceId = $param['id'];
        $model = $param['model'];
        $deviceModel = new Device();
        $deviceModel->getUpdate(['id' => $deviceId], ['mode' => $model]);
        // 查询设备imei编码
        $imei = $deviceModel->getFind(['id' => $deviceId], 'device_imei')['device_imei'];
        // mqtt发送数据
        $mqtt = new Mqtt();
        $mqtt->publish("model", $model, $imei);
        return success([]);
    }

    // 获取指定设备信息
    public function getDeviceInfo(Request $request)
    {
        $param = $request->param();
        $deviceId = $param['id'];
        $deviceModel = new Device();
        $trendsModel = new Devicetrends();
        $field = ['id,device_name,device_imei,network_card as netcard,version,is_line,device_status,mode'];
        $where = [
            'id' => $deviceId,
            'datastatus' => $deviceModel::NORMAL_DATASTATUS,
            'device_bind_status' => $deviceModel::DEVICE_BIND_STATUS_YES,
        ];
        $data = $deviceModel->getFind($where, $field);
        $trends = $trendsModel->getFind(['device_id' => $deviceId, 'is_new' => $trendsModel::YES_NEW,], 'trends_data');
        if (!$trends) {
            $data['locate'] = null;
        } else {
            $locate = json_decode($trends['trends_data'], true);
            $locarr = explode(',', $locate['gps']);
            $data['locate'] = implode(',', array_reverse($locarr));
            $data['is_have_trends'] = 1;
        }
        return success($data);
    }

    // 设备动态列表
    public function getDeviceTrends(Request $request)
    {
        $uid = $request->user_id;
        $deviceModel = new Device();
        $trendsModel = new Devicetrends();
        $field = ['lc_device.id,lc_device.device_name'];
        $where = [
            'lc_device.user_id' => $uid,
            'lc_device.datastatus' => $deviceModel::NORMAL_DATASTATUS,
            'lc_device.device_bind_status' => $deviceModel::DEVICE_BIND_STATUS_YES,
            'lc_device_trends.is_new' => $trendsModel::YES_NEW,
            'lc_device_trends.datastatus' => $trendsModel::NORMAL_DATASTATUS,
        ];
        $data = $deviceModel->table('lc_device,lc_device_trends')
            ->where('lc_device.id=lc_device_trends.device_id')
            ->where($where)
            ->field($field)
            ->select()
            ->toArray();
        if (empty($data)) return success([]);
        return success($data);
    }

    // 添加设备
    public function addDevice(Request $request)
    {
        $param = $request->param();
        $imei = $param['imei'];
        $name = $param['name'];
        $note = $param['note'];
        $uid = $request->user_id;
        if (empty($imei)) return fail([], '设备编码不能为空');
        if (empty($name)) return fail([], '设备别名不能为空');
        $deviceModel = new Device();
        $imeiModel = new Imei();
        $userModel = new User();
        // 检查imei是否已绑定
        $isBind = $imeiModel->where(['imei' => $imei])->field('status,is_stop')->find();
        if (empty($isBind)) {
            return fail([], '设备不存在');
        }
        if ($isBind['status'] == $imeiModel::DEVICE_BIND_STATUS_YES) {
            return fail([], '设备已被绑定');
        }

        if ($isBind['is_stop'] == $imeiModel::YES_STOP) {
            return fail([], '设备已被停用');
        }
        // 添加设备
        $insertData = [
            'itime' => time(),
            'user_id' => $uid,
            'device_name' => $name,
            'device_imei' => $imei,
            'device_bind_status' => $deviceModel::DEVICE_BIND_STATUS_YES,
            'notes' => $note
        ];
        // 添加用户设备数量 
        $userModel->where(['id' => $uid])->setInc('device_num');
        $add = $deviceModel->getInsert($insertData);
        unset($insertData);
        if ($add) {
            $imeiModel->where(['imei' => $imei])->update(['status' => $imeiModel::DEVICE_BIND_STATUS_YES]);
            return success([]);
        } else {
            return fail([], '设备已存在');
        }
    }

    // 设备列表
    public function deviceList(Request $request)
    {
        $uid = $request->user_id;
        $deviceModel = new Device();
        $field = ['id,device_name,cable,temp'];
        $where = [
            'user_id' => $uid,
            'datastatus' => $deviceModel::NORMAL_DATASTATUS,
            'device_bind_status' => $deviceModel::DEVICE_BIND_STATUS_YES,
        ];
        $data = $deviceModel->getSelect($where, $field);
        return success($data);
    }

    // 获取用户设备数量
    public function getDeviceNum(Request $request)
    {
        $uid = $request->user_id;
        $deviceModel = new Device();
        // 总数
        $stat['total_num'] = $deviceModel->where([
            'user_id' => $uid,
            'datastatus' => $deviceModel::NORMAL_DATASTATUS,
            'device_bind_status' => $deviceModel::DEVICE_BIND_STATUS_YES,
        ])->count();
        // 在线
        $stat['online_num'] = $deviceModel->where([
            'user_id' => $uid,
            'datastatus' => $deviceModel::NORMAL_DATASTATUS,
            'device_bind_status' => $deviceModel::DEVICE_BIND_STATUS_YES,
            'is_line' => $deviceModel::DEVICE_ONLINE
        ])->count();
        // 离线
        $stat['offline_num'] = $deviceModel->where([
            'user_id' => $uid,
            'datastatus' => $deviceModel::NORMAL_DATASTATUS,
            'device_bind_status' => $deviceModel::DEVICE_BIND_STATUS_YES,
            'is_line' => $deviceModel::DEVICE_OFFLINE
        ])->count();
        return success($stat);
    }
}
